<template>
  <div :class="{'mobile-create': showMobilePage}" class="mengli-supplier-create-wrap">
    <el-row class="create-form">
      <el-form ref="mengliSupplierForm" :model="mengliSupplierForm" :rules="mengliSupplierRules" :label-position="formAlign" class="edit-supplier lineHeight32" label-width="110px">
        <div class="form-box">
          <el-row :class="{'response-el-row': !pageType}" :type="!pageType?'flex':''">
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="供应商类型" prop="supplierType" class="client-name">
                <el-select v-model="mengliSupplierForm.supplierType" size="small" placeholder="请选择">
                  <el-option
                    v-for="item in supplierTypeOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="供应商名称" prop="supplier" class="client-name">
                <el-input v-model.trim="mengliSupplierForm.supplier" :maxlength="50" :disabled="canEdit" name="supplier" type="text"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="可抵扣税率" prop="deductionRate">
                <el-input
                  v-model="mengliSupplierForm.deductionRate"
                  name="deductionRate"
                  size="small"
                  @input="deductionRateInput"
                >
                  <span slot="suffix" style="margin-right:5px;color:#333;">%</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="创建人" prop="creator" class="client-name">
                <el-input v-model.trim="mengliSupplierForm.creator" :disabled="true" :maxlength="50" name="creator" type="text"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="备注" prop="remark">
                <el-input v-model.trim="mengliSupplierForm.remark" :maxlength="200" class="client-textarea" name="remark" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="协作人" prop="associate">
                <selectWithUserLoad
                  ref="selectUser"
                  v-model="mengliSupplierForm.associate"
                  :hide-select-list="mengliSupplierForm.associate || []"
                  :select-data-list="mengliSupplierForm.associate || []"
                  :multiple="true"
                  :value-type="'object'"
                  :style="{ 'width': showMobilePage ? 'auto' : '240px' }"
                  placeholder="请选择协作人"
                  extend-class="create-ip-order-select"
                  key-name="id"
                  label-name="userName"
                  filterable
                  collapse-tags
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="responsive-col-lg-8">
              <el-form-item label="标签" prop="tag">
                <TagSelect v-model="mengliSupplierForm.tag" :collapse-tags="false" :module-type="TAG_MODULES.MENGLI_SUPPLIER" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <fixed-pagination>
        <div class="center">
          <el-button v-if="isCanSave" :loading="loading" size="small" type="primary" @click="toSave">保存</el-button>
          <el-button type="info" class="cancel-btn-style" size="small" @click="toBack">取消</el-button>
        </div>
      </fixed-pagination>
    </el-row>
    <ExistDialog :show-dialog="showExistDialog" :data="existData" :edit-exist="editExist" @handleClose="handleClose"/>
  </div>
</template>
<script>
import { hasRouteAuth } from '@/utils/permission';
import { editSupplier, createSupplier, getSupplierInfo } from '@/api/mengli';
import { mapState } from 'vuex';
import TagSelect from '@/components/Common/tagSelect';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import ExistDialog from './module/existDialog';
import { regNumberMax } from '@/utils/numFormat';
import { TAG_MODULES } from '@/utils/const';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  name: 'SupplierCreate',
  components: { TagSelect, selectWithUserLoad, ExistDialog },
  mixins: [mobileCreate],
  props: {
    pageType: { // 如果值为 component 则这个页面作为组建使用
      type: String,
      default: ''
    }
  },
  data() {
    return {
      TAG_MODULES,
      mengliSupplierForm: {},
      antiShakeTime: 0, // 防抖时间
      loading: false,
      mengliSupplierRules: {
        supplier: [{ required: true, trigger: 'blur', message: '请填写供应商' }],
        supplierType: [{ required: true, trigger: 'blur', message: '请选择供应商类型' }]
      },
      supplierId: '',
      supplierTypeOption: [
        { value: 1, label: '个人' },
        { value: 0, label: '公司' }
      ],
      showExistDialog: false,
      existData: [],
      editExist: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    formDataIsValid() {
      const { mengliSupplierForm: { supplier }} = this;
      let isValid = true;
      if (this.$refs.mengliSupplierForm) {
        const { fields } = this.$refs.mengliSupplierForm;
        isValid = !fields.some(item => item.validateState === 'error');
      }
      const result = !!(supplier && isValid);
      return result;
    },
    isCanSave() { // 是否可以进行保存操作
      if (this.supplierId) { // 编辑状态
        return this.hasRouteAuth('mengli:supplier:edit');
      } else { // 新建
        return this.hasRouteAuth('mengli:supplier:create');
      }
    },
    canEdit() {
      return !!(this.supplierId && !this.hasRouteAuth('mengli:supplier:editSupplierName'));
    }
  },
  created() {
    if (this.pageType !== 'component') {
      this.supplierId = Number(this.$route.params.id);
    }
    if (this.supplierId && !this.pageType) {
      this.getSupplierInfo(this.supplierId);
    } else {
      this.mengliSupplierForm.creator = this.userInfo.userName;
      this.mengliSupplierForm.creatorId = this.userInfo.userId;
    }
  },
  methods: {
    hasRouteAuth,
    getSupplierInfo(id) {
      getSupplierInfo(id).then(res => {
        if (res.code === 200) {
          this.mengliSupplierForm = res.data;
          // this.mengliSupplierForm.associate = res.data.associate.map(item => item.id);
        }
      });
    },
    toSave() {
      var timestamp = new Date().getTime();
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      this.$refs.mengliSupplierForm.validate(valid => {
        if (valid) {
          if (this.loading) {
            return;
          }
          const params = JSON.parse(JSON.stringify(this.mengliSupplierForm));
          params.associate && (params.associate = params.associate.map(item => item.id));
          if (params.deductionRate) params.deductionRate = Number(params.deductionRate);
          if (!this.supplierId) {
            this.loading = true;
            this.create(params);
          } else {
            this.loading = true;
            this.edit(params);
          }
        } else {
          return false;
        }
      });
    },
    edit(params) {
      editSupplier(this.supplierId, params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.toBack();
        }
      }).catch((e) => {
        this.loading = false;
        if (e.code && e.data) {
          this.showExistDialog = true;
          this.editExist = true;
          this.existData = e.data;
        }
      });
    },
    create(params) {
      createSupplier(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('创建成功');
          if (this.pageType === 'component') {
            this.$emit('submit', { id: res.data, name: params.supplier });
            return;
          }
          this.toBack();
        }
      }).catch((e) => {
        this.loading = false;
        if (e.code && e.data) {
          this.showExistDialog = true;
          this.existData = e.data;
        }
      });
    },
    toBack() {
      if (this.pageType === 'component') {
        this.$emit('close');
        return;
      }
      this.$router.push({
        name: 'mengliSuppliers'
      });
    },
    deductionRateInput(value) {
      const str = regNumberMax(value, 100);
      this.mengliSupplierForm.deductionRate = str;
    },
    handleClose() {
      this.showExistDialog = false;
      this.editExist = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.mengli-supplier-create-wrap {
  padding: 24px;
  margin: 16px;
  background-color: #fff;
  min-height: calc(100vh - 116px);
  &::v-deep {
    .el-form {

      .el-select-dropdown__item{
        font-size: 14px;
      }
      .el-input {
        width: 240px;
      }
      .el-select {
        height: 30px;
        .el-input {
          height: 30px;
          line-height: 30px;
          width: 240px;
        }
      }
      .el-form-item {
        font-size: 14px;
        .el-form-item__label {
          font-size: 14px !important;
        }
        .el-input__icon {
          line-height: 24px;
        }
        input {
          height: 30px;
          width: 240px;
          line-height: 16px;
          font-size: 14px;
        }
      }
      .contact-list {
        margin-bottom: 16px;
        &:last-child {
          margin-bottom: 0;
        }
      }
      .add-btn {
        button {
          width: 501px;
          background-color: #f4f4f4;
          border: 1px dashed #e0e0e0;
          color: #777;
          .add-img {
            margin-right: 8px;
          }
        }
      }
      .crm-add-btn {
        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }
  }

  .client-textarea {
    width: 240px;
    &::v-deep {
      .el-textarea__inner{
        padding-left: 8px;
        font-size: 14px;
      }
    }
  }
}
</style>
